package com.hm.service.api;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class PicService {


    private final ResourceLoader resourceLoader;

    @Autowired
    public PicService(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @GetMapping(value = "/image/{filename:.+}", produces = MediaType.IMAGE_JPEG_VALUE)
    public ResponseEntity<Resource> getImage(@PathVariable String filename) {
        //Resource file = resourceLoader.getResource("D:/opencv-test/face-pic/" + filename);

        String filePath = "D:/opencv-test/face-pic/";
        Path imageStoragePath = Paths.get(filePath);

        System.out.println("---filename->" + filename);

        try {
            Path imagePath = imageStoragePath.resolve(filename); // 假设图片名为image.jpg
            Resource resource = new UrlResource(imagePath.toUri());
            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok().body(resource);
            } else {
                throw new RuntimeException("Could not read the image: " + imagePath);
            }
        } catch (Exception e) {
            throw new RuntimeException("Error loading image", e);
        }
    }
}
